import requests
import re
import threading
import time
from src.models.models import SystemConfig

class XunleiNASTokenRefresher:
    def __init__(self, app, interval_hours=12):
        self.app = app
        self.interval = interval_hours * 3600
        self.thread = threading.Thread(target=self.run, daemon=True)
        self.stop_event = threading.Event()

    def start(self):
        self.thread.start()

    def stop(self):
        self.stop_event.set()
        self.thread.join()

    def run(self):
        while not self.stop_event.is_set():
            try:
                self.refresh_token()
            except Exception as e:
                print(f"[XunleiNASTokenRefresher] 刷新 token 失败: {e}")
            self.stop_event.wait(self.interval)

    def refresh_token(self):
        with self.app.app_context():
            host = SystemConfig.get_config('xunlei_nas_host')
            if not host:
                print("[XunleiNASTokenRefresher] 未配置 xunlei_nas_host")
                return
            url = f"{host}/webman/3rdparty/pan-xunlei-com/index.cgi/"
            resp = requests.get(url, timeout=10)
            if resp.status_code != 200:
                print(f"[XunleiNASTokenRefresher] 请求失败: {resp.status_code}")
                return
            # 修正正则，精准提取 uiauth 函数 return 的 token
            match = re.search(r'function\s+uiauth\(value\)\s*{\s*return\s*["\']([^"\']+)["\']', resp.text)
            if not match:
                print("[XunleiNASTokenRefresher] 未找到 uiauth 函数 return 值")
                return
            new_credential = match.group(1).strip()
            old_credential = SystemConfig.get_config('xunlei_nas_credential')
            if new_credential != old_credential:
                SystemConfig.set_config('xunlei_nas_credential', new_credential, '迅雷NAS授权凭证')
                print("[XunleiNASTokenRefresher] xunlei_nas_credential 已更新")
            else:
                print("[XunleiNASTokenRefresher] xunlei_nas_credential 未变化")